import React, { useEffect, useState } from 'react';
import styles from './index.less';
import { Button, Dropdown, Checkbox, Tooltip, Tree, message } from 'antd';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import _ from 'lodash';

import { QuestionCircleOutlined, PlusOutlined, SettingOutlined } from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';
import { useStaticState, useTRState } from '#/utils/trHooks.jsx';
import { saveDynamicColumns } from '@/pages/ETrade/PowerForecastAdjusted/services.js';

const BtnSort = ({
  options,
  onDelete,
  onChange,
}: {
  options: any[];
  onDelete: any;
  onChange: any;
}) => {
  const [startIndex, setStart] = useState(null),
    [overIndex] = useState(null);
  //顺位 交换位置
  const changePosition = (dragIndex: any, hoverIndex: any) => {
    const data = _.cloneDeep(options);
    const temp = data[dragIndex];
    data.splice(dragIndex, 1);
    data.splice(hoverIndex, 0, temp);
    onChange(data);
  };
  //开始 鼠标按下
  const onDragStart = (e: any, index: any) => {
    if (startIndex) {
      return;
    }
    setStart(index);
    // setOver(index)
    //分情况 向前(默认) 向后
    //向后
  };
  const onDragOver = (e: any) => {
    //使用onDragEnd 需设置preventDefault()
    e.preventDefault();
  };
  //元素内移动
  const onDragEnter = (e: any, hoverIndex: any) => {
    if (startIndex === hoverIndex) {
      //remenber Delete
      return;
    }
    // if (overIndex === hoverIndex) {
    //     return;
    // }
    // setOver(hoverIndex)
    setStart(hoverIndex); //remenber Delete
    changePosition(startIndex, hoverIndex); //remenber Delete
  };

  //离开
  const onDragLeave = (e: any) => {
    e.preventDefault();
    // setOver(null)
  };
  //松开鼠标
  const onDragEnd = (e: any) => {
    e.preventDefault();
    setStart(null);
    // //如果没有选择容器
    // if (overIndex === null || startIndex === overIndex) {
    //     return
    // }
    // setOver(null)
    // changePosition(startIndex, overIndex);
  };
  return (
    <>
      {options.map((t: any, i: number) => (
        <div
          draggable
          onDragEnd={(e) => {
            onDragEnd(e);
          }}
          onDragEnter={(e) => {
            onDragEnter(e, i);
          }}
          onDragStart={(e) => {
            onDragStart(e, i);
          }}
          onDragOver={(e) => {
            onDragOver(e);
          }}
          onDragLeave={(e) => {
            onDragLeave(e);
          }}
          key={t.value}
          className={`${styles.btn_sort} ${overIndex === i && styles.before}
                        `}
        >
          <Button className={`${styles.btn} ${startIndex === i && styles.drag}`}>{t.label}</Button>
          {options.length > 1 && (
            // <svg
            //     xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" fill="none">
            //     <circle cx="6" cy="6" r="6" fill="#FD4F43" />
            //     <rect x="310767" y="535693" width="578466" height="128571" rx="0.642857" fill="white" />
            // </svg>
            <svg
              onClick={() => {
                onDelete(i);
              }}
              className={styles.delete}
              xmlns="http://www.w3.org/2000/svg"
              width="12"
              height="12"
              viewBox="0 0 12 12"
              fill="none"
            >
              <circle cx="6" cy="6" r="6" fill="#FD4F43" />
              <rect
                x="3.10767"
                y="5.35693"
                width="5.78466"
                height="1.28571"
                rx="0.642857"
                fill="white"
              />
            </svg>
          )}
        </div>
      ))}
    </>
  );
};
const DimensionalSort = (props: any) => {
  const {
    option,
    onClick,
    optionsArray,
    columns = [],
    filterColumns,
    menuCode = '',
    regionCode,
  } = props;
  const arrData = Array.from(optionsArray, (t, i) => ({ label: t, value: i })),
    [options, setOptions] = useState(Array.from(option, (t, i) => ({ label: t, value: i }))),
    [selectData, setSelectData] = useState([]); //维度下拉框选中的值
  const [state, setState] = useTRState({
    indeterminate: false,
    checkAll: false,
    open: false,
    selectedKeys: [],
    loading: false,
  });
  const staticData = useStaticState({
    allDataObj: {},
    allKeys: [],
    disabledKeys: [],
  });
  /*method */
  const _hanlderConfigDelete = (index: number) => {
    const _data = [...options];
    _data.splice(index, 1);
    setOptions(_data);
  };
  const _onChange = (data: any) => {
    setOptions(data);
  };
  //点击聚合
  const _hanlderOnClick = () => {
    onClick(options.map((t) => t.label));
  };
  //维度排序视图
  const _renderAddBtn = () => {
    let temp = arrData;
    temp = temp.filter((t) => !options.some((_t) => _t.label === t.label));
    const _checkboxonChange = (checked: any, value: any) => {
      //选中 移除
      checked.target.checked
        ? setSelectData([...selectData, value] as any)
        : setSelectData(selectData.filter((t) => t !== value));
    };
    const _visibleChange = (visible: boolean) => {
      if (!selectData.length) {
        return;
      }
      //将选中的项添加到维度选项 并清除选中项
      !visible &&
        setOptions(
          options.concat(
            selectData.map((t: any, i: number) => ({ label: t, value: options.length + i })),
          ),
        );
      setSelectData([]);
    };
    const menu = (
      <div className={styles.checkbox_group}>
        {temp.map((t: any) => (
          <div
            key={t.value}
            onClick={(e) => {
              e.stopPropagation();
            }}
          >
            <Checkbox
              checked={selectData.includes(t.label as never)}
              onChange={(e) => {
                _checkboxonChange(e, t.label);
              }}
            >
              {t.label}
            </Checkbox>
          </div>
        ))}
      </div>
    );
    return (
      <Dropdown
        overlay={menu}
        onVisibleChange={_visibleChange}
        disabled={!temp.length}
        placement="bottomLeft"
        trigger={['click']}
      >
        <Button
          className={temp.length ? styles.add_btn : styles.add_btn_disabled}
          disabled={!temp.length}
        >
          <PlusOutlined />
        </Button>
      </Dropdown>
    );
  };

  const flattenDeep = (list: any = [], selectedObj: any = {}) => {
    list?.forEach((l: any) => {
      selectedObj[l.key] = _.cloneDeep(l);
      l?.children?.length && flattenDeep(l.children, selectedObj);
    });
    return selectedObj;
  };

  const flattenDeepKey = (list: any = []) => {
    const selectedKeys = [];
    list?.forEach((l: any) => {
      let childrenObj = {};
      childrenObj = flattenDeep(l?.children || [], childrenObj);
      // 默认选中
      if (
        (l?.checkbox === 1 && l?.key) ||
        (Object.values(childrenObj)?.length &&
          Object.values(childrenObj)?.filter((c) => c?.checkbox === 1)?.length ===
            Object.values(childrenObj)?.length)
      ) {
        selectedKeys.push(l.key);
      }
      // 所有选项
      if ((!l?.disabled || (l?.disabled && l?.checkbox === 1)) && l?.key) {
        staticData.allKeys.push(l.key);
      }
      // 禁止选择中 选中的
      if (l?.disabled && l?.checkbox === 1 && l?.key) {
        staticData.disabledKeys.push(l.key);
      }
    });
    return selectedKeys;
  };
  const setColumns = () => {
    if (
      !['ForecastDataAdjustReanalyze', 'electricityCostAnalysis'].includes(menuCode) ||
      !columns?.length
    )
      return;
    let selectedKeys: string[] = [];
    const selectedObj: any = {};
    staticData.allDataObj = flattenDeep(columns, selectedObj);
    selectedKeys = flattenDeepKey(Object.values(staticData.allDataObj));

    setState({
      selectedKeys,
      indeterminate: !!selectedKeys.length && selectedKeys.length < staticData.allKeys.length,
      checkAll: selectedKeys.length === staticData.allKeys.length,
    });
  };
  useEffect(() => {
    setColumns();
    return () => {
      staticData.allKeys = [];
      staticData.disabledKeys = [];
    };
  }, [columns]);
  const columnsVisibleChange = (flag: boolean) => {
    setState({
      open: flag,
    });
  };
  const onCheckAllChange = (e: CheckboxChangeEvent) => {
    Object.values(staticData.allDataObj)?.forEach((s) => {
      if (s.checkbox !== undefined) {
        s.checkbox = e?.target.checked ? 1 : 0;
      }
    });
    setState({
      selectedKeys: e?.target.checked ? staticData.allKeys : staticData.disabledKeys,
      indeterminate: false,
      checkAll: e?.target.checked,
    });
  };
  const onCheck = (selectedKeys: React.Key[]) => {
    Object.values(staticData.allDataObj)?.forEach((s) => {
      if (s.checkbox !== undefined) {
        s.checkbox = selectedKeys.includes(s?.key) ? 1 : 0;
      }
    });

    setState({
      selectedKeys,
      indeterminate: !!selectedKeys.length && selectedKeys.length < staticData.allKeys.length,
      checkAll: selectedKeys.length === staticData.allKeys.length,
    });
  };
  const transformationTree = (list: any = []) => {
    const array = list?.map((a) => {
      const slide = _.cloneDeep(staticData.allDataObj[a.key]);
      let children = [];
      if (a?.children?.length) {
        children = transformationTree(a.children);
        slide.children = _.cloneDeep(children);
      }
      return slide;
    });
    return array;
  };
  const onSuccess = async () => {
    setState({
      loading: true,
    });
    const array = transformationTree(_.cloneDeep(columns));
    const params = {
      regionCode,
      menuCode,
      array,
    };
    const res = await saveDynamicColumns(params);
    if (res?.statusCode === HttpCode.SUCCESS) {
      columnsVisibleChange(false);
      filterColumns && filterColumns(state.selectedKeys);
    } else {
      message.error(res?.message || '保存失败');
    }
    setState({
      loading: false,
    });
  };
  const renderColumns = () => {
    return (
      <div className={styles.columns_container}>
        <div className={styles.columns_container_header}>
          <Checkbox
            indeterminate={state.indeterminate}
            onChange={onCheckAllChange}
            checked={state.checkAll}
          >
            全选
          </Checkbox>
        </div>
        <div className={styles.columns_container_tree}>
          <Tree checkable onCheck={onCheck} checkedKeys={state.selectedKeys} treeData={columns} />
        </div>
        <div className={styles.columns_container_footer}>
          <Button
            size={'small'}
            style={{ marginRight: 8 }}
            onClick={() => columnsVisibleChange(false)}
            loading={state.loading}
          >
            取消
          </Button>
          <Button
            size={'small'}
            type={'primary'}
            onClick={() => onSuccess()}
            loading={state.loading}
          >
            确认
          </Button>
        </div>
      </div>
    );
  };
  return (
    <div className={styles.group}>
      <div className={styles.flex}>
        <div className={styles.label}>
          聚合维度选择
          <Tooltip
            title={`功能支持的数据聚合维度包括“${optionsArray.join(
              '”、“',
            )}”，您可通过增减维度数量、调整维度顺序来控制数据聚合，获得想要的效果。`}
          >
            <QuestionCircleOutlined style={{ color: '#FD4F43', marginLeft: '0.04rem' }} />
          </Tooltip>
        </div>
        <BtnSort options={options} onChange={_onChange} onDelete={_hanlderConfigDelete} />
        {_renderAddBtn()}
      </div>

      <div className={styles.group_pol}>
        {['ForecastDataAdjustReanalyze', 'electricityCostAnalysis'].includes(menuCode) ? (
          <Dropdown
            overlay={renderColumns}
            onVisibleChange={() => columnsVisibleChange(true)}
            placement="bottomRight"
            trigger={['click']}
            visible={state.open}
          >
            <SettingOutlined style={{ fontSize: '.12rem', cursor: 'pointer' }} />
          </Dropdown>
        ) : null}
        <Button onClick={_hanlderOnClick} type="primary" className={styles.polymerize}>
          聚合
        </Button>
      </div>
    </div>
  );
};
export default DimensionalSort;
